#include <stdio.h>
#include <string.h>

#include "tklog.h"

char tk_log_buf[TK_LOG_BUF_LEN + 1];
int tk_log_level = DEBUG;
FILE *tk_log_file = NULL;
char cache_str_time[sizeof("2014-12-12 12:12:12")];
const int cache_str_time_len;

FILE* setlogfile(FILE *file)
{
        if (tk_log_file == file)
                return NULL;

        FILE *old_file = tk_log_file;
        tk_log_file = file;

        return old_file;
}

int setloglevel(int level)
{
        tk_log_level = level;
}

void GenerateLogMsg(char *filename, int lineno, int log_level)
{
        static char *debug_str =        "[debug]";
        static char *info_str =         "[info ]";
        static char *error_str =        "[error]";
        static char *fatal_str =        "[fatal]";
        static char *system_str =       "[system]";
        int len = 0;

        memset(tk_log_buf, 0x00, sizeof(tk_log_buf));
        switch(log_level) {
                case DEBUG:
                        memcpy(tk_log_buf, debug_str, 7);
                        len = 7;
                        break;
                case INFO:
                        memcpy(tk_log_buf, info_str, 7);
                        len = 6;
                        break;
                case ERROR:
                        memcpy(tk_log_buf, error_str, 7);
                        len = 7;
                        break;
                case FATAL:
                        memcpy(tk_log_buf, fatal_str, 7);
                        len = 7;
                        break;
                case SYSTEM:
                        memcpy(tk_log_buf, system_str, 8);
                        len = 8;
                        break;
        }
        if (cache_str_time[0] != '\0') {
                memcpy(tk_log_buf + len, cache_str_time, cache_str_time_len - 1);
                len += cache_str_time_len - 1;
        }

        sprintf(tk_log_buf + len, " %s:%d| ", filename, lineno);
}

